var TableRole = function () {
    return {
        init: function () {
			          
            oTable = $('#table_role').dataTable({
                "aLengthMenu": [
                    [-1,5, 15, 20],
                    ["全部",'5条', '15条', '20条'] 
                ],
                "iDisplayLength": -1,
                "sPaginationType": "bootstrap",
				"bStateSave": false, 
                "oLanguage": {
					"sSearch":"搜索",
                    "sLengthMenu": "每页显示 _MENU_ 记录",    
					"sEmptyTable":"没有数据",
					"sInfo": "当前数据为从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录",   
					"sInfoEmpty": "没有数据",   
					"sInfoFiltered" : "",
					"sInfoPostFix" : "",
					"sLoadingRecords":"",
					"sProcessing": "正在加载数据...", 
					"sZeroRecords": "没有检索到数据", 
                    "oPaginate": {   
						"sFirst": "首页",   
						"sPrevious": "上一页",   
						"sNext": "下一页",   
						"sLast": "尾页"  
					}   
                },
				"sAjaxSource":ajaxUrl,
				"sAjaxDataProp": "data",
				"aoColumns": [
					{"sTitle":'角色ID',"mDataProp": 'roleId'},
					{"sTitle":'角色名称',"mDataProp": 'roleName'},
					{"sTitle":'创建时间',"mDataProp": 'createTime'},
					{"sTitle":'权限',"mDataProp": 'grantName'},
					{"sTitle":'操作',"mDataProp": 'roleFlag'}
				],
                "aoColumnDefs": [{
                        'bSortable': false,
						'aTargets': ['_all']
						
                    },
					{"aTargets":[0],"sClass":'text-center',"sWidth":'5%',"bSearchable": false},
					{"aTargets":[1],"bSearchable": true},
					{"aTargets":[2],"bSearchable": false},
					{"aTargets":[3],"mRender":function(data,type,full){
						return '<a class="details-row btn btn-xs yellow" href="" data_id="'+full['roleId']+'"><i class="fa fa-plus-square-o"></i> 详细权限</a>';//<span class='row-details row-details-close' data_id='"+full['roleId']+"'></span> 详细权限";
                    },"sClass":'text-center',"bSearchable": false},  
					
					{"aTargets":[4],"mRender":function(data,type,full){
                     return '<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>';
                    },"sClass":'text-center',"bSearchable": false}
                ]
            });
			
			function fnFormatDetails ( oTable, nTr ){
				var aData = oTable.fnGetData( nTr );
				var roleName = aData['grantName'];
				
				var sOut = '<table>';
				for(var i=0;i<roleName.length;i++){
					if(roleName[i]['bPath'].match(/,/g).length==1){
						sOut += '<tr><td><span class="label label-primary"><i class="fa '+roleName[i]["authIco"]+'"></i> '+roleName[i]["authName"]+'</span></td><td>';
							for(var j=0;j<roleName.length;j++){
								if(roleName[j]['bPath'].match(/,/g).length==2 && roleName[j]['parentId']==roleName[i]['authId']){
									sOut += '  <span class="label label-default"><i class="fa '+roleName[j]["authIco"]+'"></i> '+roleName[j]["authName"]+'</span>';
								}
							}
						sOut += '</td></tr>';
					}
				}
					sOut += '</table>';
				return sOut;
			}
			
            jQuery('#table_role_wrapper .dataTables_filter input').addClass("form-control input-medium input-inline"); // modify table search input
            jQuery('#table_role_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
            jQuery('#table_role_wrapper .dataTables_length select').select2({
                showSearchInput : false 
            }); 
			
            var nEditing = null;
			//切换
			$('#table_role').on('click', ' tbody td .details-row', function (e) {
				e.preventDefault();
				var nTr = $(this).parents('tr')[0];
				if ( oTable.fnIsOpen(nTr) ){
					$(this).children('i').eq(0).addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
					oTable.fnClose( nTr );
				}else{                
					$(this).children('i').eq(0).addClass("fa-minus-square-o").removeClass("fa-plus-square-o");
					oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
				}
			});

			//添加
            $('#table_role_new').click(function (e) {
                e.preventDefault();
				$('#responsive form').attr('class','role-form');//切换表单
				$('.modal-header h4')[0].innerHTML = '添加新角色';
				
				var jqName = $('#responsive input[name="roleName"]').eq(0);//清空角色名
				jqName.val('');
				jqName.attr('disabled',false);//解除禁用
				var jqAjax = $('#responsive input[name="ajax"]').eq(0);
				jqAjax.val('addRoles');//切换提交地址
				var jqRole = $('#responsive input[name="roleId"]').eq(0);
				jqRole.val('');//清空ID
				$('#responsive button[type="submit"]').eq(0).removeClass('edit');//移除修改按钮
				
				/*清空选择表单*/
				var jqTds = $('#responsive input[type="checkbox"]');
				for (var i = 0, iLen = jqTds.length; i < iLen; i++) {	
						jqTds.eq(i).attr('checked',false);
						jqTds.eq(i).parent('span').removeClass('checked');					
				}
				
				$('#responsive').modal('show');//显示模态框              
            });
			
			
			//删除
            $('#table_role a.delete').live('click', function (e) {
                e.preventDefault();
				var nRow = $(this).parents('tr')[0];
				var aData = oTable.fnGetData(nRow);
				layer.confirm('确定删除该角色？',function(index){
					$.post(ajaxUrl,{roleId:aData['roleId'],ajax:'delRoles'},function(data){
						if(data){
							layer.msg('角色删除成功！',{icon: 1,time: 2000});
							oTable.fnDeleteRow(nRow);
						}else{
							layer.msg('角色删除失败！',{icon: 1,time: 2000});
							return;
						}
				   });					
				});
            });
            
			
			//取消按钮
			$('button[data-dismiss="modal"]').live('click', function (e) {
                e.preventDefault();
				$('#responsive').modal('hide');//关闭模态框
				validator.resetForm();//重置验证表单
				$('#responsive .form-group').removeClass('has-error');//去除遗留样式	
            });
			
			//Ajax 编辑
			$('button.edit').live('click', function (e) {
				e.preventDefault();
				$.ajax({
					url:ajaxUrl,
					type : "post",  
					dataType : "json",  
					data: $(".edit-form").serialize(),  
					success : function(data) {		
						if(data.status=='1'){
							layer.msg(data.info, 
								{icon: 1,time: 2000},
								function(){
									$('#responsive').modal('hide');
									oTable.fnReloadAjax();
								}
							);   	
						}else{
							layer.msg(data.info, 
								{icon: 2,time: 2000}
							);   
							return;
						}
					}  
				});          
			});
			
			
			//修改
			Array.prototype.in_array=function(e){//增加Js in_array()
				for (var i = 0;i<this.length;  i++) {
					if(this[i]==e){
						return true;
					}
				}
				return false;
			}
            $('#table_role a.edit').live('click', function (e) {
                e.preventDefault();
				$('#responsive form').attr('class','edit-form');//表单切换
				$('.modal-header h4')[0].innerHTML = '修改角色';//表头修改
				
                var nRow = $(this).parents('tr')[0];//取得当前行
				var aData = oTable.fnGetData(nRow);//取得数据
				var jqName = $('#responsive input[name="roleName"]').eq(0);
				jqName.val(aData['roleName']);//表头赋值
				jqName.attr('disabled',true);//禁止修改
				var jqAjax = $('#responsive input[name="ajax"]').eq(0);
				jqAjax.val('editRoles');//切换提交地址
				var jqRole = $('#responsive input[name="roleId"]').eq(0);
				jqRole.val(aData['roleId']);//角色id赋值
				$('#responsive button[type="submit"]').eq(0).addClass('edit')//标记编辑按钮
				
				/*勾选默认权限*/
				var jqTds = $('#responsive input[type="checkbox"]');
				for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
					//先清空
					jqTds.eq(i).attr('checked',false);
					jqTds.eq(i).parent('span').removeClass('checked');	
					//添加
					var a=jqTds[i].value.split(',')[1];
					var b=aData['grant'].split(',');
					if(b.in_array(a)){
						jqTds.eq(i).attr('checked',true);
						jqTds.eq(i).parent('span').addClass('checked');
					}
				}
				//打开模态框
				$('#responsive').modal('show');
            });
        }

    };

}();